package com.fh.shop.api.interceptor;

import com.fh.shop.api.annotation.Check;
import com.fh.shop.api.annotation.NeedLogin;
import com.fh.shop.api.common.ResponseEnum;
import com.fh.shop.api.config.IdempotenceException;
import com.fh.shop.api.exception.TokenException;
import com.fh.shop.api.util.KeyUtil;
import com.fh.shop.api.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class TokenInterceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 处理 swagger
        if (!(handler instanceof HandlerMethod)){
            // 拦截
            return true;
        }
        //获取方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //判断方法是否有注解
        if (!method.isAnnotationPresent(Check.class)){
            //没有注解直接放行
            return true;
        }
        //验证
        String header = request.getHeader("x-idempotence");
        //非空验证
        if (StringUtils.isEmpty(header)){
            throw new IdempotenceException(ResponseEnum.IDEMPOTENCE_HEADER_IS_NULL);
        }
        long delete = RedisUtil.delete(KeyUtil.buildTokenKey(header));
        if (delete == 0){
            //重复发送请求了，违反了接口幂等性 -- 第一次有效请求，将key删除了，第二次请求，在删除时为0
            throw new IdempotenceException(ResponseEnum.IDEMPOTENCE_IS_ERROR);
        }
        //放行
        return true;
    }

}
